package com.sixth.service.impl;

import com.github.pagehelper.util.StringUtil;
import com.sixth.annotation.PageInfoAdvice;
import com.sixth.bean.*;
import com.sixth.bean.bo.*;
import com.sixth.bean.common.BasePageInfo;
import com.sixth.bean.vo.*;
import com.sixth.constant.Constant;
import com.sixth.controller.wx.WXTopicDetailVO;
import com.sixth.mapper.MarketGoodsMapper;
import com.sixth.mapper.MarketTopicMapper;
import com.sixth.service.TopicService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @Author Chen
 * @Date 2022-09-08  15-15-20
 * @description 专题管理实现类
 */
@Service
public class TopicServiceImpl implements TopicService {


    @Autowired
    MarketTopicMapper topicMapper;

    @Autowired
    MarketGoodsMapper goodsMapper;

    /**
     * @Author Chen
     * @Date 2022-09-08  15-15-52
     * @param
     * @return {@link null }
     * @description  根据条件查询专题
     */
    @Override
    @PageInfoAdvice
    public Object getTopicList(TopicPageInfo topicPageInfo) {

        MarketTopicExample topicExample = new MarketTopicExample();

        topicExample.setDistinct(true);

        topicExample.setOrderByClause(topicPageInfo.getSort()+" "+topicPageInfo.getOrder());


        MarketTopicExample.Criteria criteria = topicExample.createCriteria();

        criteria.andDeletedEqualTo(false);

        if (!StringUtil.isEmpty(topicPageInfo.getTitle())){
            criteria.andTitleLike("%"+topicPageInfo.getTitle()+"%");
        }

        if (!StringUtil.isEmpty(topicPageInfo.getSubtitle())){
            criteria.andSubtitleLike("%"+topicPageInfo.getSubtitle()+"%");
        }

        List<MarketTopicVO> marketTopics = topicMapper.selectByExampleUseTypeHandler(topicExample);

        return marketTopics;
    }

    /**
     * @Author Chen
     * @Date 2022-09-08  16-26-57
     * @param
     * @return {@link null }
     * @description 批量删除专题
     */
    @Override
    public int batchDelTopic(TopicBatchDeleteBO deleteIds) {

        List<Integer> ids = deleteIds.getIds();
        if (ids.size()>=Constant.ONE){

            MarketTopicExample topicExample = new MarketTopicExample();

            MarketTopicExample.Criteria criteria = topicExample.createCriteria();

            criteria.andIdIn(ids);

            MarketTopic marketTopic = new MarketTopic();
            marketTopic.setDeleted(true);

            int delResult = topicMapper.updateByExampleSelective(marketTopic, topicExample);

            if (delResult==ids.size()){
                return Constant.OK;
            }
        }

        return Constant.NON;
    }

    /**
     * @Author Chen
     * @Date 2022-09-08  19-44-44
     * @param
     * @return {@link null }
     * @description 删除一个专题
     */
    @Override
    public int deleteTopic(DelTopicBO delTopicBO) {

        MarketTopic marketTopic = new MarketTopic();
        marketTopic.setDeleted(true);
        marketTopic.setId(delTopicBO.getId());

        int updateResult = topicMapper.updateByPrimaryKeySelective(marketTopic);

        if (updateResult == Constant.ONE){
            return Constant.OK;
        }

        return Constant.NON;
    }

    /**
     * @Author Chen
     * @Date 2022-09-08  19-45-07
     * @param
     * @return {@link null }
     * @description 添加专题
     */
    @Override
    public TopicVO addTopic(TopicBO topicBO) {

        MarketTopic marketTopic = new MarketTopic();
        marketTopic.setContent(topicBO.getContent());
        marketTopic.setGoods(topicBO.getGoods().toString());
        marketTopic.setPicUrl(topicBO.getPicUrl());
        marketTopic.setPrice(topicBO.getPrice());
        marketTopic.setReadCount(topicBO.getReadCount());
        marketTopic.setSubtitle(topicBO.getSubtitle());
        marketTopic.setTitle(topicBO.getTitle());
        marketTopic.setAddTime(new Date());
        marketTopic.setDeleted(false);
        marketTopic.setSortOrder(0);
        marketTopic.setUpdateTime(new Date());

        int addResult = topicMapper.insert(marketTopic);

        if (addResult == Constant.ONE){

            MarketTopic topic = topicMapper.selectByPrimaryKey(marketTopic.getId());
            TopicVO topicVO = new TopicVO();
            BeanUtils.copyProperties(topic,topicVO);
            return topicVO;
        }

        return null;
    }


    /**
     * @Author Chen
     * @Date 2022-09-08  23-22-08
     * @param
     * @return {@link null }
     * @description 编辑专题时回显数据
     */
    @Override
    public EditTopicVO getTopic(Integer id) {

        MarketTopicVO marketTopicVO = topicMapper.selectByPrimaryKeyUseHandler(id);

        if (marketTopicVO!=null){

            MarketGoodsExample goodsExample = new MarketGoodsExample();

            MarketGoodsExample.Criteria criteria = goodsExample.createCriteria();

            List<Integer> gids = new ArrayList<>();
            for (Integer good : marketTopicVO.getGoods()) {
                gids.add(good);
            }


            EditTopicVO editTopicVO = new EditTopicVO();

            if (gids.size()>=Constant.ONE){
                criteria.andIdIn(gids);
                criteria.andDeletedEqualTo(false);
                List<MarketGoods> marketGoods = goodsMapper.selectByExample(goodsExample);

                ArrayList<TopicGoodsVO> topicGoodsVOS = new ArrayList<>();
                for (MarketGoods marketGood : marketGoods) {
                    TopicGoodsVO topicGoodsVO = new TopicGoodsVO();
                    BeanUtils.copyProperties(marketGood,topicGoodsVO);
                    topicGoodsVOS.add(topicGoodsVO);
                }

                editTopicVO.setGoodsList(topicGoodsVOS);

            }

            editTopicVO.setTopic(marketTopicVO);

            return editTopicVO;
        }

        return null;
    }

    @Override
    public MarketTopicVO updateTopic(EditTopicBO editTopicBO) {

        MarketTopic marketTopic = new MarketTopic();

        BeanUtils.copyProperties(editTopicBO, marketTopic);

        String goods = "[]";
        Integer[] topicBOGoods = editTopicBO.getGoods();

        if (topicBOGoods.length>0){
            goods="[";
            for (Integer integer : topicBOGoods) {
                goods = goods+""+integer+",";
            }
            goods = goods.substring(0,goods.length()-1);
            goods = goods+"]";
        }

        marketTopic.setGoods(goods);

        int updateResult = topicMapper.updateByPrimaryKeySelective(marketTopic);

        if (updateResult == Constant.ONE){

            MarketTopicVO topicVO = topicMapper.selectByPrimaryKeyUseHandler(editTopicBO.getId());

            return topicVO;
        }

        return null;
    }

    /**
     *
     * @author qys
     * @date 2022/9/11 14:01
     * @param basePageInfo
     * @return Object
     */
    @PageInfoAdvice
    @Override
    public Object wxTopicList(BasePageInfo basePageInfo) {
        MarketTopicExample marketTopicExample = new MarketTopicExample();
        MarketTopicExample.Criteria marketTopicExampleCriteria = marketTopicExample.createCriteria();
        marketTopicExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        List<MarketTopic> marketTopics = topicMapper.selectByExampleWithBLOBs(marketTopicExample);
        LinkedList<WXTopicListVO> res = new LinkedList<>();
        // 格式转换，测试BeanUtils
        for (MarketTopic marketTopic : marketTopics) {
            WXTopicListVO wxTopicListVO = new WXTopicListVO();
            try {
                org.apache.commons.beanutils.BeanUtils.copyProperties(wxTopicListVO, marketTopic);
            }
            catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            res.add(wxTopicListVO);
        }
        return res;
    }

    @Override
    public WXTopicDetailVO wxTopicDetail(Integer topicId) {
        WXTopicDetailVO res = new WXTopicDetailVO();
        // 先查出topic
        MarketTopicExample marketTopicExample = new MarketTopicExample();
        MarketTopicExample.Criteria marketTopicExampleCriteria = marketTopicExample.createCriteria();
        // 条件：id和未删除
        marketTopicExampleCriteria.andDeletedEqualTo(Constant.EXIST);
        marketTopicExampleCriteria.andIdEqualTo(topicId);
        List<MarketTopicByTypeHandler> marketTopics = topicMapper.selectByExampleWithBLOBsByTypeHandler(marketTopicExample);
        // 没有返回null
        if (marketTopics.isEmpty()) {
            return null;
        }
        MarketTopicByTypeHandler topic = marketTopics.get(0);
        res.setTopic(topic);
        // 根据topic中的goods数组查出相应的goods

        Integer[] goodsIds = topic.getGoods();
        if (goodsIds == null || goodsIds.length == 0) {
            return res;
        }
        List<MarketGoods> marketGoodsList = goodsMapper.selectGoodsByInIds(goodsIds);
        // 转换格式
        // TODO : BeanUtils不成功是缺失信息的
        LinkedList<TopicGoodsVO> topicGoodsVOS = new LinkedList<>();
        for (MarketGoods marketGoods : marketGoodsList) {
            TopicGoodsVO topicGoodsVO = new TopicGoodsVO();
            try {
                org.apache.commons.beanutils.BeanUtils.copyProperties(topicGoodsVO, marketGoods);
            }
            catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            topicGoodsVOS.add(topicGoodsVO);
        }
        res.setGoods(topicGoodsVOS);
        return res;
    }

    @PageInfoAdvice
    @Override
    public Object wxTopicRelate(Integer topicId, BasePageInfo basePageInfo) {
        // 根据访问量降序
        MarketTopicExample marketTopicExample = new MarketTopicExample();
        marketTopicExample.setOrderByClause("cast(read_count as decimal) desc");
        marketTopicExample.createCriteria().andDeletedEqualTo(Constant.EXIST);
        return topicMapper.selectByExampleWithBLOBsByTypeHandler(marketTopicExample);
    }
}
